package com.moyun.finance.service;

import com.moyun.finance.entity.*;
import com.moyun.finance.repository.*;
import com.moyun.finance.utils.BaseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class OrgRoleUserMidService {
    @Autowired
    OrgRoleUserMidRepository orumr;
    @Autowired
    OrgRoleRepository orr;
    @Autowired
    OrgUserRepository our;

    public Response save(List<OrgRoleUserMid> orums){
        for(OrgRoleUserMid orum : orums){
            orum.setId(BaseUtil.uuid());
            orumr.save(orum);
        }
        return new Response("用户角色信息添加成功!",true);
    }

//    public Response update(List<OrgRoleUserMid> orums){
//        for(OrgRoleUserMid orum : orums){
//            orumr.save(orum);
//        }
//        return new Response("用户部门信息修改成功!",true);
//    }

    public Response delete(OrgRoleUserMid orum){
        orumr.delete(orum);
        return new Response("用户角色信息删除成功!",true);
    }

    //本角色下所有人
    public List<OrgUser> findAllUserByRole(String deptId){
        List<OrgUser> users =  new ArrayList<>();
        List<OrgRoleUserMid> orums = orumr.findByRoleId(deptId);
        for(OrgRoleUserMid orum : orums){
            String userId = orum.getUserId();
            OrgUser ou = our.findById(userId).orElse(null);
            users.add(ou);
        }
        return users;
    }

    //查询用户属于哪个角色
    public List<OrgRole> findUserRoleByUser(String userId){
        List<OrgRole> roles =  new ArrayList<>();
        List<OrgRoleUserMid> orums = orumr.findByUserId(userId);
        for(OrgRoleUserMid orum : orums){
            String roleId = orum.getRoleId();
            if(roleId != null){
                OrgRole or = orr.findById(roleId).orElse(null);
                roles.add(or);
            }
        }
        return roles;
    }

    public List<String> findUserRoleIdByUser(String userId){
        List<OrgRoleUserMid> orums = orumr.findByUserId(userId);
        List<String> roleIds = new ArrayList<>();
        for(OrgRoleUserMid orum : orums){
            roleIds.add(orum.getRoleId());
        }
        return roleIds;
    }

    //拼接角色名
    public String findUserRoleNameByUser(String userId){
        List<OrgRoleUserMid> orums = orumr.findByUserId(userId);
        String roleName = "";
        int index = 0;
        for(OrgRoleUserMid orum : orums){
            if(index > 0){
                roleName += ",";
            }
            String deptId = orum.getRoleId();
            OrgRole or = orr.findById(deptId).orElse(null);
            roleName += or.getRoleName();
        }
        return roleName;
    }
}
